<?
	session_start();
	include("mysqlcon.php");
	include("error.php");
	
	$userlist_username = $_POST['userlist_username'];
	$userlist_password = $_POST['userlist_password'];
	if($userlist_username==NULL||$userlist_password==NULL) header("Location: login.php");
	else{
	$x=mysql_select_db($dbname,$conn);

	$userlist_username = $_POST['userlist_username'];
	$userlist_password = $_POST['userlist_password'];

	$charset = "SET character_set_results=utf-8";
	$sql="SELECT * FROM userlist";
	$result = mysql_query( $sql );
		while ( $rs = mysql_fetch_array( $result ) ) 
	{ 
			if(strcmp($rs['userlist_username'],$userlist_username)==0)
			{
				if(strcmp($rs['userlist_password'],md5($userlist_password))==0)
				{	
					$id = $rs['userlist_id'];
					$group_id = $rs['group_id'];
					$userlist_usernamename =$rs['userlist_username'];
					$_SESSION["valid_USER"]=$id;
					$_SESSION["HBD_USER"]=$rs[userlist_id];
					$nav = $_SERVER['HTTP_USER_AGENT']; 
					setcookie("HBD_USER",$rs['userlist_id'],time()+(3600*24*7));
					$secure = md5($rs['userlist_password']);
					setcookie("HBD_PASS",$secure,time()+(3600*24*7));
					
					//keep user agent
					
					$useragent = $_SERVER[HTTP_USER_AGENT];  

					if (preg_match('|MSIE ([0-9].[0-9]{1,2})|',$useragent,$matched)) {
					    $browser_version=$matched[1];
					    $browser = "IE";
					} elseif (preg_match( '|Opera ([0-9].[0-9]{1,2})|',$useragent,$matched)) {
					    $browser_version=$matched[1];
					    $browser = "Opera";
					} elseif(preg_match('|Firefox/([0-9\.]+)|',$useragent,$matched)) {
					        $browser_version=$matched[1];
					        $browser = "Firefox";
					} elseif(preg_match('|Safari/([0-9\.]+)|',$useragent,$matched)) {
					        $browser_version=$matched[1];
					        $browser = "Safari";
					} else {
					        // browser not recognized!
					    $browser_version = 0;
					    $browser= "other";
					}
					
					$browser .= $browser_version;
					
					$strSQL="INSERT INTO historylog (userlist_id,historylog_ip,historylog_useragent)";
 					$strSQL=$strSQL."VALUES('$id','$_SERVER[REMOTE_ADDR]','$browser')";
					
					$result2 = mysql_query($strSQL);
					mysql_query($result2);
					
					
					if($group_id == 1)
						header("Location: admin.php");
					
					else 
						header("Location: index.php");
				}
			}
				
	}
	 $_SESSION["code_error"];
	 error_page("รหัสผ่านผิด กรุณาลองใหม่อีกครั้ง หรือ ติดต่อผู้ดูและระบบ");
	}
?>